/**
 * wx 和jssdk相关的helper
 */
import Vue from 'vue';

const wxHelper = {

    /**
     * 微信jssdk类型列表
     * @type {Object}
     */
    types: {
        base: ['checkJsApi'],	//基础接口
        share: ['updateAppMessageShareData', 'updateTimelineShareData', 'onMenuShareWeibo'],	//分享
        image: ['chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'getLocalImgData'],	//图片
        audio: ['startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'onVoicePlayEnd', 'uploadVoice', 'downloadVoice'],	//音频接口
        zAudio: ['translateVoice'],	//智能语音接口
        netType: ['getNetworkType'],	//设置信息接口
        location: ['openLocation', 'getLocation'],	//地理位置接口
        beacons: ['startSearchBeacons', 'stopSearchBeacons', 'onSearchBeacons'],	//摇一摇
        interface: ['closeWindow', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem'],	//界面操作
        qrCode: ['scanQRCode'],	//微信扫一扫
        product: ['openProductSpecificView'],	//微信小店
        card: ['chooseCard', 'addCard', 'openCard'],	//微信卡券
        pay: ['chooseWXPay'],	//微信支付
        input: ['openAddress']	//快速输入
    },

    /**
     * jssdk对象
     * @type {[type]}
     */
    wx: null,

    /**
     * 初始化微信jssdk
     * @param  {Object}   params    [types：类型列表, callback：回调方法, debug：是否debug]
     * @param  {function} params.callback [回调方法：第一个参数：注册是否成功，第二个参数：成功为wx对象，失败为错误信息]
     * @return {Object}            [微信jssdk对象]
     */
    init(params) {
        if (!Vue.prototype.commonHelper.clientType().isWeixin) {
            params.callback(false, '当前为非微信客户端');

            return false;
        }

        if (typeof wx === "undefined") {
            var wxjs = document.createElement("script");
            wxjs.src = "https://res.wx.qq.com/open/js/jweixin-1.6.0.js";
            wxjs.type = "text/javascript";
            wxjs.onload = () => {
                wxHelper.authorize(params);
            };

            document.getElementsByTagName("body")[0].appendChild(wxjs);
        } else {
            this.authorize(params);
        }
    },

    /**
     * 注入授权
     * @param {object} params 参数信息
     */
    authorize(params) {
        Vue.prototype.appFetch({
            url: 'getJsSdkConfig',
            method: 'get',
            data: {
                APIs: this.getApiListByTypes(params.types),
                debug: !!params.debug,
                url: encodeURIComponent(window.entryUrl)
            }
        }, (res) => {
            if (res.code == 200) {
                wx.config(res.data);

                let isRight = true;
                wx.ready((res) => {
                    setTimeout(() => {
                        if (isRight) {
                            params.callback(true, wx);
                        }
                    }, 200);
                });

                wx.error((res) => {
                    isRight = false;
                    params.callback(false, res.errMsg);
                });
            } else {
                params.callback(false, res.msg);
                console.log(res.msg);
            }
        }, (error) => {
            params.callback(false, '授权接口请求失败');
            console.log(error)
        });
    },

    /**
     * 根据类型列表获取接口列表
     * @param  {[type]} types [description]
     * @return {[type]}       [description]
     */
    getApiListByTypes(types) {
        let apis = [];

        types.forEach((type) => {
            if (this.types[type]) {
                apis = [...apis, ...this.types[type]];
            }
        });

        return apis;
    },

    /**
     * 设置微信分享
     * @param  {[type]} info [description]
     * @return {[type]}      [description]
     */
    shareMessage(data) {
        wx.updateAppMessageShareData(data);
        wx.updateTimelineShareData(data);
    },

};

if (!Vue.prototype.wxHelper) {
    Vue.prototype.wxHelper = wxHelper;
}

export default wxHelper;






















